package info.nene_loveplus.service;

import info.nene_loveplus.meta.blog.EntryMeta;
import info.nene_loveplus.model.AudioFile;
import info.nene_loveplus.model.blog.Comment;
import info.nene_loveplus.model.blog.Entry;

import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.repackaged.com.google.common.collect.Lists;

public class BlogService {

	private static EntryMeta E = EntryMeta.get();

	private Logger log = Logger.getLogger(BlogService.class.getName());

	/**
	 * 記事を１件作成する.
	 * 
	 * @param entry
	 *            -
	 */
	public void createEntry(Entry entry) {
		List<Object> models = Lists.newArrayList();

		Date now = new Date();
		if (entry.getKey() == null) {
			entry.setCreatedAt(now);
			entry.setUpdatedAt(now);
		} else {
			entry.setUpdatedAt(now);
		}
		models.add(entry);

		if (entry.getAudioFileRef().getModel() != null) {
			AudioFile audio = entry.getAudioFileRef().getModel();
			models.add(audio);
		}

		Datastore.put(models);
		log.info("記事を新規作成");
	}

	/**
	 * 記事のリストを取得する.
	 * 
	 * 最新の50件を取得する.
	 * 
	 * @return -
	 */
	public List<Entry> list() {
		return Datastore.query(Entry.class).sort(E.key.desc).limit(50).asList();
	}

	/**
	 * 記事を１件取得する.
	 * 
	 * @param key
	 *            目的記事のID
	 * @return -
	 */
	public Entry findById(String key) {
		if (key == null) {
			return null;
		}
		try {
			return Datastore.get(Entry.class, KeyFactory.stringToKey(key));
		} catch (Exception e) {
			log.log(Level.SEVERE, "Entry検索時に例外", e);
			return null;
		}
	}

	public void postComment(Key entryKey, String name, String comment) {

		log.fine("postComment key=" + entryKey + ", comment=" + comment);

		Entry entry = Datastore.get(Entry.class, entryKey);

		Comment newComment = new Comment();
		newComment.setName(name);
		newComment.setComment(new Text(comment));
		newComment.setPostedAt(new Date());
		newComment.getEntryRef().setModel(entry);

		entry.getCommentListRef().getModelList().add(newComment);

		Datastore.put(entry, newComment);
	}

	public void delete(Key key) {
		Datastore.delete(key);
	}

	public List<Entry> listAll() {
		return Datastore.query(Entry.class).sort(E.createdAt.desc.getSort())
				.asList();
	}

}
